package com.chahu.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chahu.entity.Article;
import com.chahu.mapper.ArticleMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {

    @Async("taskExcutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article){
        Integer viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts+1);
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.eq(Article::getId, article.getId());
        //设置一个为了在多线程的环境下线程安全
        //改之前再确认这个值有没有被其他线程抢先修改，类似于CAS操作 cas加自旋，加个循环就是cas
        articleLambdaQueryWrapper.eq(Article::getViewCounts, viewCounts);
        // update article set view_count=100 where view_count=99 and id =111
        //实体类加更新条件
        articleMapper.update(articleUpdate, articleLambdaQueryWrapper);
    }
}
